import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './router'
import store from './store'
import { asyncRoutes } from './router'
nProgress.configure({
  showSpinner: false// 不显示右边圆环
})
const whiteList = ['/login']
router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  nProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      if (!store.getters.userInfo?.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRouter = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/SET_ROUTES', filterRouter)
        router.addRoutes([...filterRouter, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
        // console.log(store.getters.userInfo?.userId, '1111')
      }
      // console.log(store.getters.userInfo?.userId, '2222')
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach(() => {
  nProgress.done()
})
